<?php

namespace App\Services\WanSdk;

use App\Commons\CommonConstant;
use App\Services\GameChannelService;
use App\Services\GameService;
use App\Services\ServiceBase;
use App\Services\WechatApi\WechatApiOauth;
use Jenssegers\Agent\Facades\Agent;

class WanSdkService extends ServiceBase
{
    // 获得游戏入口地址
    public function getGameUrl($game_id, $game_channel_id = 0)
    {
        return config('app.url') . "/h5sdk/index/{$game_id}/{$game_channel_id}";
    }

    // 当前是否处于微信客户端
    public function isWechatUa()
    {
        $agent = Agent::getUserAgent();
        if (strpos($agent, 'MicroMessenger') === false) {
            return false;
        }

        return true;
    }

    /**
     * 获取用户运行环境，H5、微信、端
     *
     * @param array $params 请求参数
     * @return int
     */
    public function getEnvType($params)
    {
        // 在微信环境下运行
        if ($this->isWechatUa()) {
            return CommonConstant::ENV_TYPE_WECHAT;
        }

        // 如果带有设备码信息，则认为是在端上运行
        foreach (['idfv', 'idfa', 'android_id', 'oaid', 'google_adid', 'imei'] as $device_key) {
            if (isset($params[$device_key])) {
                return CommonConstant::ENV_TYPE_APK;
            }
        }

        // 是否在ios的主屏幕上打开
        if (isset($params['ios_in_standalone']) && $params['ios_in_standalone'] == 1) {
            return CommonConstant::ENV_TYPE_IOS_STANDALONE;
        }

        // 在H5环境
        return CommonConstant::ENV_TYPE_H5;
    }

    // 当前是否处于手机端
    public function isPhone()
    {
        $agent = Agent::getUserAgent();
        foreach (['Windows', 'Ubuntu'] as $val) {
            if (strpos($agent, $val) !== false) {
                return false;
            }
        }

        return true;
    }

    public function getPhoneType()
    {
        $agent = Agent::getUserAgent();
        if (preg_match('/(iPhone|iPad|iPod)/', $agent)) {
            return CommonConstant::DEVICE_TYPE_IOS;
        }

        if (preg_match('/Android/', $agent)) {
            return CommonConstant::DEVICE_TYPE_ANDROID;
        }

        if (preg_match('/(Mac OS)/', $agent)) {
            return CommonConstant::DEVICE_TYPE_IOS;
        }

        return CommonConstant::DEVICE_TYPE_OTHER;
    }

    /**
     * 根据游戏获取公众号登录授权链接
     *
     * @param int $game_id 游戏id
     * @param array $params 透传参数
     * @return string
     */
    public function getWechatOauthUrl($game_id, $game_channel_id, $params = [], $cb_uri = 'h5sdk/oauth', $scope = 'snsapi_base'): string
    {
        $game = GameService::getInstance()->get($game_id);
        $game_channel = GameChannelService::getInstance()->get($game_channel_id);
        $appid        = $game_channel['jspay_appid'] ?? 0;
        $query        = http_build_query($params);
        if (!empty($game['host'])) {
            $url = $game['host'];
        } else {
            $url = config('app.url');
        }

        $cb_url = $url . "/{$cb_uri}?game_id={$game_id}&{$query}";
        $url    = WechatApiOauth::getInstance()->getUserOauthUrl($appid, $cb_url, $scope, 'program_start');

        return $url;
    }

    /**
     * 获得微信公众号授权登录的用户openid
     *
     * @param int $game_id 游戏id
     * @param string $code 公众号授权登录返回的code
     * @return array
     */
    public function getWechatOffiaccountInfo($game_id, $game_channel_id, $code): array
    {
        $game_channel = GameChannelService::getInstance()->get($game_channel_id);
        $appid = $game_channel['jspay_appid'];
        $secret = $game_channel['jspay_appsecret'];
        $res = WechatApiOauth::getInstance()->oauthUser($appid, $secret, $code);
        if (!$res) {
            return [];
        }

        return [
            'scope'         => $res['scope'],
            'openid'        => $res['openid'],
            'unionid'       => $res['unionid']??'',
            'refresh_token' => $res['refresh_token']??'',
        ];
    }

    public function getManifestUrl($game_id, $game_channel_id, $params)
    {
        $url = config('app.url') . "/h5sdk/manifest/{$game_id}/{$game_channel_id}/manifest.json";
        if (!empty($params)) {
            $query_str = http_build_query($params);
            $url = "{$url}?{$query_str}";
        }

        return $url;
    }
}
